package com.lcm.jnode.controller.admin;

import java.io.ByteArrayInputStream;
import java.util.Map;

import org.apache.log4j.Logger;

import com.baidu.bae.api.util.BaeEnv;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StringKit;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;
import com.lcm.jnode.interceptor.AdminInterceptor;
import com.lcm.jnode.kit.ImageKit;
import com.lcm.jnode.kit.MailKit;
import com.lcm.jnode.kit.StringsKit;
import com.lcm.jnode.model.MailVerify;
import com.lcm.jnode.model.Options;
import com.lcm.jnode.model.User;
import com.lcm.jnode.model.WBLogin;
import com.lcm.jnode.utils.BCSUtils;
import com.lcm.jnode.utils.ConfigUtil;
import com.lcm.jnode.validator.EmailValidator;

/**
 * 网站后台
 * @author L.cm
 * @date 2013-6-1 下午5:29:58
 */
@Before(AdminInterceptor.class)
public class AdminController extends Controller{
	
	private static final Logger log = Logger.getLogger(AdminController.class);
	private static final String IMG_TYPE = ".jpg|.jepg|.gif|.png|.bmp";
    
    /**
     * 后台首页
     */
    public void index() {}

    /**
     * 登录
     */
    @ClearInterceptor
    @Before(EmailValidator.class)
    public void session() {
        String email = getPara("email");
        String pwd = getPara("pwd");
        Integer remember = getParaToInt("remember", 0);
        User user = User.dao.login(email, StringsKit.pwdEncrypt(pwd));
        if(StringKit.notNull(user)) {
            if(remember == 1){
                String code = StringsKit.cookieEncrypt(email, pwd);
                setCookie("userId", code, 60 * 60 * 24 * 30, "/", ConfigUtil.get("domain"));
            }
            User.dao.updateUser(user);
            setSessionAttr("user", user);
            setAttr("status", 0);
        }else {
            setAttr("status", 1);
        }
        renderJson(new String[]{"status"});
    }
    
    /**
     * 用户绑定
     */
    @ClearInterceptor
    @Before(EmailValidator.class)
    public void binding() {
    	String email = getPara("email");
    	int wbId = getParaToInt("id");
    	WBLogin wb = WBLogin.dao.findById(wbId);
    	boolean status = false;
    	if (null == wb) {
    		renderJson("status", 2);
    		return;
    	}
    	User user = User.dao.findByEmail(email);
    	if (null == user) {
    		String name = wb.getStr(WBLogin.NICKNAME);
    		user = User.dao.saveUser(email, name);
    		if (null != user) {
    			status = wb.set(WBLogin.USERID, user.getInt(User.ID)).update();
			}
    	} else {
    		status = wb.set(WBLogin.USERID, user.getInt(User.ID)).update();
    	}
    	if (status){
    		// TODO 邮件校验
    		Map<String, Object> model = Maps.newHashMap();
    		Options options = Options.dao.findByCache();
    		// model.put("type", wb.getStr(WBLogin.TYPE));
    		model.put("options", options);
    		MailVerify verify = new MailVerify();
    		verify.set(MailVerify.USER_ID, user.getInt(User.ID));
    		status = MailVerify.dao.createVerify(verify);
    		String verifyUrl = options.getStr(Options.WUMII_SITE) + "/finish?code=" + verify.getStr(MailVerify.VERIFY_CODE); 
     		model.put("verifyUrl",  verifyUrl);
    		// options.wumii_site, options.wb_qq, options.wb_sina
    		MailKit.sendTemplateEmail(null, "DreamLu博客邮箱绑定", email, model, "signup_send.jade");
    	}
    	renderJson("status", status ? 0 : 1);
    }
    
    /**
     * 邮箱校验
     */
    @ClearInterceptor
    @Before(EmailValidator.class)
    public void email_verify() {
    	String email = getPara("email");
    	
//    	MailKit.sendTemplateEmail(from, subject, to, model, tempname);
    }
    
    /**
     * 
     */
    public void reset() {
    	
    }

    /**
     * 友情连接
     */
    public void links(){}
    
    /**
     * kindedit 图片上传 Bae 环境
     */
    @Before(POST.class)
    public void editor(){
    	// BAE 临时目录上传
    	String tmpfsPath = BaeEnv.getTmpfsPath();
        try {
        	UploadFile file = getFile("imgFile", tmpfsPath, 1024 * 1024);
            String oldName = file.getFileName();
        	String fileType = oldName.substring(oldName.lastIndexOf("."), oldName.length());
        	if(IMG_TYPE.indexOf(fileType.toLowerCase()) == -1){
        		 setAttr("error", 1);
                 setAttr("message", "上传出错，请检查图片格式！");
                 render(new JsonRender(new String[]{"error", "message"}).forIE());
                 return;
        	}
            String newName = System.currentTimeMillis() + fileType;
            // 第一次上传文件
            BCSUtils.uploadByFile(file.getFile(), newName);
            String url = "http://bcs.duapp.com/" + BCSUtils.bucket + "/" + newName;
            byte[] bs = ImageKit.watermark(url, "dreamlu.net");
            // 第二次水印之后重新上传
            BCSUtils.uploadByInputStream(new ByteArrayInputStream(bs), "image/jpeg", bs.length, newName);
            setAttr("error", 0);
            setAttr("url", url);
            render(new JsonRender(new String[]{"error", "url"}).forIE());
        } catch (Exception e) {
            log.error(e);
            setAttr("error", 1);
            setAttr("message", "上传出错，请稍候再试！");
            render(new JsonRender(new String[]{"error", "message"}).forIE());
        }
    }
}
